//
//  PhotoBrowserViewController.swift
//  MyWeiboApp
//
//  Created by 胡海波 on 15/7/6.
//  Copyright © 2015年 胡海波. All rights reserved.
//

import UIKit
import FFAutoLayout
import SVProgressHUD

class PhotoBrowserViewController: UIViewController {


    func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }

    func saveCurrentPhoto(){
        
        // 1.拿到当前的indexPath
        let indexPath = collectionView.indexPathsForVisibleItems().last
        
        // 2.拿到当前的cell
        let cell = collectionView.cellForItemAtIndexPath(indexPath!) as! PhotoViewCell
        
        // 3.取出image
        let image = cell.imageView.image!
        
        // 4.写到本地相册
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
        
    }
    
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
        if error != nil {
            SVProgressHUD.showErrorWithStatus("保存失败!")
        }
        else {
            
            SVProgressHUD.showSuccessWithStatus("保存成功!")
        }
    }

    init(urls:[NSURL],index: Int ){

        imagesURLs = urls

        currentIndex = index

        super.init(nibName: nil, bundle: nil)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // 一组图片的URL
    private var imagesURLs: [NSURL]

    ///  当前图片的索引
    private var currentIndex: Int

    override func viewDidLoad() {
        super.viewDidLoad()


    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        prepareLayout()
        
        // 跳转到用户选定的页面
        let indexPath = NSIndexPath(forItem: currentIndex, inSection: 0)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }

    func prepareLayout() {
        layout.itemSize = collectionView.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal

        collectionView.pagingEnabled = true
        collectionView.showsHorizontalScrollIndicator = false
        
        //collectionView.bounces = false


    }
 

    override func loadView() {

        view = UIView(frame: UIScreen.mainScreen().bounds)

        view.addSubview(collectionView)
        view.addSubview(closeBtn)
        view.addSubview(saveBtn)
        

        closeBtn.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        saveBtn.addTarget(self, action: "saveCurrentPhoto", forControlEvents: UIControlEvents.TouchUpInside)

        collectionView.ff_Fill(view)
        closeBtn.ff_AlignInner(ff_AlignType.BottomLeft, referView: view, size: CGSize(width: 60, height: 30), offset: CGPoint(x: 12, y: -12))
        saveBtn.ff_AlignInner(ff_AlignType.BottomRight, referView: view, size: CGSize(width: 60, height: 30), offset: CGPoint(x: -12, y: -12))
        
        prepareCollectionView()

    }
    
    func prepareCollectionView(){
        
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.registerClass(PhotoViewCell.self, forCellWithReuseIdentifier: HBPhotoBrowserCellIdentifier)
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    /// 定义collectionView
    lazy private var layout = UICollectionViewFlowLayout()
    lazy private var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)

    // 定义关闭和保存按钮
    lazy private var closeBtn:UIButton = UIButton(title: "关闭", fontSize: 14)
    lazy private var saveBtn:UIButton = UIButton(title: "保存", fontSize: 14)

}

private let HBPhotoBrowserCellIdentifier = "HBPhotoBrowserCellIdentifier"
extension PhotoBrowserViewController: UICollectionViewDataSource,UICollectionViewDelegate,PhotoViewCellDelegate {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imagesURLs.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HBPhotoBrowserCellIdentifier, forIndexPath: indexPath) as! PhotoViewCell

        cell.backgroundColor = UIColor.clearColor()
        cell.imageURL = imagesURLs[indexPath.item]
        cell.photoViewDelegate = self
        
        return cell

    }
    
    // 全屏模式不会触发此方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
//        let cell = collectionView.cellForItemAtIndexPath(indexPath) as! PhotoViewCell
//        
//        cell.photoViewDelegate = self
    }
    
    func photoViewDidTapImage() {
        // 关闭当前控制器
        close()
    }

}
